import Vue from '@/main';
import Bus from '../bus';
import WebRTC2 from '../../sdk/NIM_Web_WebRTC2_v4.0.1.js';

// let WebRTC2 = null;

// ios 获取媒体会有问题
export const importWebRTC = () => {
  // const u = navigator.userAgent;
  // const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  // if (isAndroid) {
  //   import('../../sdk/NIM_Web_WebRTC2_v4.0.1.js').then(module => {
  //     WebRTC2 = module;
  //   });
  // }
};

const WebRTCCall = {
  client: null,
  localStream: null, // 本地流
  remoteStream: null // 远程流
};

// 免提开启或关闭
export const openOrCloseSpeaker = () => {
  const { remoteStream, isSpeaker, localStream } = Vue.$store.state.videocall;
  if (!remoteStream) {
    Vue.$toast(isSpeaker ? '当前不能打开mic' : '当前不能打开扬声器');
    return;
  }
  if (!isSpeaker) {
    WebRTC2.getSpeakers().then(data => {
      console.log('getSpeakers: ', data);
      const deviceId = data[0].deviceId;
      localStream
        .switchDevice('audio', deviceId)
        .then(() => {
          Vue.$store.commit('videocall/setSpeaker', true);
        })
        .catch(err => {
          console.log('打开扬声器失败: ', err);
        });
    });
  } else {
    WebRTC2.getMicrophones().then(data => {
      console.log('getMicrophones: ', data);
      const deviceId = data[0].deviceId;
      localStream
        .switchDevice('audio', deviceId)
        .then(() => {
          Vue.$store.commit('videocall/setSpeaker', false);
        })
        .catch(err => {
          console.log('打开mic失败: ', err);
        });
    });
  }
};

// 开始发布视频流
const publish = localStream => {
  console.log('publish===', localStream);
  // 发布本地媒体给房间对端
  WebRTCCall.client
    .publish(localStream)
    .then(() => {
      console.log('本地 publish 成功');
    })
    .catch(err => {
      console.error('本地 publish 失败: ', err);
      Vue.$toast('本地 publish 失败');
    });
};

const subscribe = remoteStream => {
  remoteStream.setSubscribeConfig({
    audio: true,
    video: true
  });
  WebRTCCall.client
    .subscribe(remoteStream)
    .then(() => {
      console.log('本地 subscribe 成功');
    })
    .catch(err => {
      console.error('本地 subscribe 失败: ', err);
      Vue.$toast('订阅对方的流失败');
    });
};

export const initLocalStream = localUid => {
  if (!WebRTC2) return;
  let deviceId = Vue.$store.state.videocall.videoDeviceId;
  console.log('videoDeviceId===', deviceId);
  WebRTC2.getCameras().then(videoDeviceList => {
    console.log('initLocalStream', videoDeviceList.length, videoDeviceList[0]);
    const videoDevice = videoDeviceList[0];
    if (!deviceId) {
      deviceId = videoDevice.deviceId;
    } else {
      deviceId = videoDeviceList.filter(item => item.deviceId !== deviceId)[0]
        .deviceId;
    }
    console.log(deviceId, videoDeviceList);
    Vue.$store.commit('videocall/setVideoDeviceInfo', {
      deviceId,
      videoDevices: videoDeviceList
    });
    // 初始化本地的Stream实例，用于管理本端的音视频流
    WebRTCCall.localStream = WebRTC2.createStream({
      uid: localUid,
      audio: true, // 是否启动mic
      video: true, // 是否启动camera
      screen: false, // 是否启动屏幕共享
      cameraId: deviceId
    });
    // 设置本地视频质量
    WebRTCCall.localStream.setVideoProfile({
      resolution: WebRTC2.VIDEO_QUALITY_720p, // 设置视频分辨率
      frameRate: WebRTC2.CHAT_VIDEO_FRAME_RATE_15 // 设置视频帧率
    });
    // 设置本地音频质量
    WebRTCCall.localStream.setAudioProfile('speech_low_quality');
    // 启动媒体，打开实例对象中设置的媒体设备
    WebRTCCall.localStream
      .init()
      .then(() => {
        // 音视频开启完成，可以播放了
        Bus.$emit('playLocalStream', WebRTCCall.localStream);
        // 发布
        publish(WebRTCCall.localStream);
      })
      .catch(err => {
        console.log('音视频初始化失败: ', err);
        Vue.$toast('音视频初始化失败');
        WebRTCCall.localStream = null;
      });
  });
};

export const initWebRTC2 = appKey => {
  console.log('WebRTC2====', WebRTC2);
  if (!WebRTC2) return;
  console.log('初始化音视频sdk');
  WebRTCCall.client = WebRTC2.createClient({
    appkey: appKey,
    debug: true
  });
  // 加入房间
  WebRTCCall.client.on('peer-online', evt => {
    console.log(`${evt.uid} 加入房间`);
  });
  // 离开房间
  WebRTCCall.client.on('peer-leave', evt => {
    console.log(`${evt.uid} 离开房间`);
    // if (this.remoteStream.getId() === evt.uid) {}
    Bus.$emit('hangUp');
  });
  // 对方发布的订阅消息
  WebRTCCall.client.on('stream-added', evt => {
    const remoteStream = evt.stream;
    console.log('收到对方发布的订阅消息: ', remoteStream.getId());
    const rStream = WebRTCCall.remoteStream;
    if (rStream && rStream.getId() !== remoteStream.getId()) {
      console.log('房间里第三个人加入，忽略');
      return;
    }
    WebRTCCall.remoteStream = remoteStream;
    subscribe(remoteStream);
  });
  // 对方停止订阅
  WebRTCCall.client.on('stream-removed', evt => {
    const remoteStream = evt.stream;
    console.log('对方停止订阅: ', remoteStream.getId());
    remoteStream.stop();
  });
  // 收到了对端的流，准备播放
  WebRTCCall.client.on('stream-subscribed', evt => {
    console.log('收到了对端的流，准备播放', evt.stream.getId());
    const remoteStream = evt.stream;
    Vue.$store.commit('videocall/setWait', false);
    // 用于播放对方视频画面的div节点
    Bus.$emit('playRemoteStream', remoteStream);
  });
  // 对端切换成语音
  WebRTCCall.client.on('mute-video', evt => {
    console.log('该事件表示指定主播将视频静音', evt);
    // this.switchAudioOrVideo();
  });
};

export default WebRTCCall;
